﻿using MediatR;
using WMS.API.Application.Command.BasicManagement.ProductManage;
using WMS.Domain.Entities.BasicManagement;
using WMS.ErrorCode;
using WMS.Interfactructure.Interfaces;

namespace WMS.API.Application.CommandHandlers.BasicManagement.ProductManage
{
    public class ProductManageCommandHandler : IRequestHandler<ProductManageCommand, APIResult<APIPaging<ProductManageModel>>>
    {
        private readonly IBaseRepository<ProductManageModel> _productManageModelRepository;

        public ProductManageCommandHandler(IBaseRepository<ProductManageModel> productManageModelRepository)
        {
            _productManageModelRepository = productManageModelRepository;
        }
        /// <summary>
        /// 产品显示处理命令处理
        /// </summary>
        /// <param name="request">参训条件</param>
        /// <returns>返回产品管理列表</returns>
        public Task<APIResult<APIPaging<ProductManageModel>>> Handle(ProductManageCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var productManageModel = _productManageModelRepository.GetAll();
                productManageModel = productManageModel.WhereIf(!string.IsNullOrEmpty(request.ProductName), m => m.ProductName.Contains(request.ProductName));
                productManageModel = productManageModel.WhereIf(!string.IsNullOrEmpty(request.Team), m => m.Team.Contains(request.Team));
                productManageModel = productManageModel.WhereIf(!string.IsNullOrEmpty(request.Typeof), m => m.Typeof.Contains(request.Typeof));
                productManageModel = productManageModel.WhereIf(!string.IsNullOrEmpty(request.SKU), m => m.SKU.Contains(request.SKU));
                var page = new APIPaging<ProductManageModel>();
                page.TotalCount = productManageModel.Count();
                page.PageData = productManageModel.OrderByDescending(m => m.Id).Skip((request.PageIndex - 1) * request.PagePage).Take(request.PagePage).ToList();
                return Task.FromResult(new APIResult<APIPaging<ProductManageModel>>("产品信息显示成功")
                {
                    Code = ResultCode.Success,
                    Data = page,
                });
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}
